package com.zhouxiao.multithreading.forkjoin;

import java.util.concurrent.RecursiveTask;

public class Counter extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 1000;

    private int from;
    private int to;

    Counter(int from, int to) {

        this.from = from;
        this.to = to;
    }

    @Override
    protected Integer compute() {
        int count = 0;
        if (to - from < THRESHOLD) {
            for (int i = from; i <= to; i++) {
                count += i;
            }
        } else {
            int mid = (from + to) / 2;
            Counter first = new Counter(from, mid);
            Counter second = new Counter(mid + 1, to);
            first.fork();
            second.fork();
            count = first.join() + second.join();
        }
        return count;
    }
}
